class Snake {
  snake: HTMLElement
  head: HTMLElement
  bodies: HTMLCollection
  constructor() {
    this.snake = document.getElementById('snake')!;
    this.head = document.querySelector('#snake > div') as HTMLElement
    // 这样获取可以动态更新
    this.bodies = this.snake.getElementsByTagName('div')
  }

  get X(): number {
    return this.head.offsetLeft
  }

  get Y(): number {
    return this.head.offsetTop
  }

  set X(left: number) {
    //减少操作坐标,因为一般只移动一个坐标
    if (this.X != left) {
      // 但蛇头向反方向移动时,强制向前移动
      if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft == left) {
        if (this.X > left)
          left += 20
        else
          left -= 20
      }
      this.moveBody()
      this.head.style.left = left + 'px'
      this.checkHeadBody()
      if (left < 0 || left > 290)
        throw Error("蛇撞墙了! Game Over")
    }
  }

  set Y(top: number) {
    if (this.Y != top) {
      if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === top) {
        if (this.Y > top)
          top += 20
        else
          top -= 20
      }
      this.moveBody()
      this.head.style.top = top + 'px'
      this.checkHeadBody()
      if (top < 0 || top > 290)
        throw Error("蛇撞墙了! Game Over")

    }
  }

  addBody() {
    this.snake.appendChild(document.createElement('div'))
  }

  moveBody() {
    for (let i = this.bodies.length - 1; i > 0; i--) {
      (this.bodies[i] as HTMLElement).style.left = (this.bodies[i - 1] as HTMLElement).offsetLeft + 'px';
      (this.bodies[i] as HTMLElement).style.top = (this.bodies[i - 1] as HTMLElement).offsetTop + 'px';
    }
  }

  checkHeadBody() {
    for (let i = this.bodies.length - 1; i > 0; i--) {
      if ((this.bodies[i] as HTMLElement).offsetLeft == this.X && (this.bodies[i] as HTMLElement).offsetTop == this.Y)
        throw Error("撞到自己了")
    }
  }
}

export default Snake